var behaviorsbasic = require("../../behaviors/basic")

// xc/components/widgets/upload.js
Component({
  behaviors: [behaviorsbasic],
  /**
   * 组件的属性列表
   */
  properties: {
    multiple: {
      type: Boolean,
      value: true
    },
    mode: {
      type: String,
      value: "single"   //single,more
    },
    uploadText: {
      type: String,
      value: ""   //single,more
    },
    
    imageFit: {
      type: String,
      value: "scaleToFill"   //single,more
    },    
    customStyle:{
      type: String,
      value: ""   
    }, 
    customitemStyle:{
      type: String,
      value: ""   
    },

    // xfield:{
    //   type:String,
    //   value:"",
    // },
    max: {
      type: Number,
      value: 1
    },
    fileList: {
      type: Array,
      value: []
    }
    // fileList:[]
  },

  /**
   * 组件的初始数据
   */
  data: {
    //url
    imglist: []
  },

  /**
   * 组件的方法列表
   */
  methods: {
    savefilefunc(file) {
      var app = getApp()
      var that = this
      var mode = that.data.mode
      app.toolv2.uploadFile(file.path).then(function (item) {
        var fileList = []
        if (mode == 'more') {
          fileList = that.data.fileList
        }
        fileList.push({ ...file, url: item.obj.fullpath });
        that.setData({ fileList });
        that.afterfilechange();
      })
    },
    afterfilechange() {
      var that = this
      var mode = that.data.mode
      var fileList = that.data.fileList
      var imglist=[]
      fileList.forEach(item => {
        imglist.push(item.url)
      })
      var paradeal = { xfield: that.data.xfield }
      if (mode == 'more') {
        paradeal["val"] = imglist
      }
      else {
        paradeal["val"] =  imglist[0] ? imglist[0] : ""
      }
     
      that.triggerEvent("xvmodel", paradeal)
      that.triggerEvent("change", paradeal)
    },
    delimg(event) {
      var detail = event.detail
      var fileList = this.data.fileList
      fileList.splice(detail.index, 1)    
      this.setData({ fileList })   
      this.afterfilechange();
    },
    afterRead(event) {
      var that = this
      const { file } = event.detail
      if (file.constructor == Array) {
        file.forEach(item => {
          that.savefilefunc(item)
        })
      }
      else {
        that.savefilefunc(file)
      }
    }
  }
})
